#include "audiocapture.h"
#include <QDebug>
#include <QAudioDevice>
#include <QMediaDevices>
#include <QAudioSource>
#include <QAudioFormat>
#include <QIODevice>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QHttpMultiPart>
#include <QJsonDocument>
#include <QJsonObject>
#include <QTimer>
#include <QMutexLocker>
#include <QByteArray>
#include <QString>
#include <QQueue>

AudioCapture::AudioCapture(QObject *parent)
    : QObject(parent)
    , m_audioSource(nullptr)
    , m_audioIODevice(nullptr)
    , m_isCapturing(false)
    , m_transmissionEnabled(false)
    , m_transmissionHost("localhost")
    , m_transmissionPort(8766)
    , m_transmissionTimer(nullptr)
    , m_processingThread(nullptr)
{
    setupAudioFormat();
    
    // 创建传输定时器
    m_transmissionTimer = new QTimer(this);
    connect(m_transmissionTimer, &QTimer::timeout, this, &AudioCapture::onTransmissionTimer);
    
    // 创建音频处理线程
    m_processingThread = new AudioProcessingThread(this);
    connect(m_processingThread, &AudioProcessingThread::audioDataProcessed,
            this, &AudioCapture::audioDataReady);
    m_processingThread->start();
}

AudioCapture::~AudioCapture()
{
    stopCapture();
    if (m_processingThread) {
        m_processingThread->stopProcessing();
        m_processingThread->wait(3000);
        delete m_processingThread;
    }
}

bool AudioCapture::startCapture()
{
    if (m_isCapturing) {
        return true;
    }
    
    if (!initializeAudioCapture()) {
        emit captureError("无法初始化音频捕获");
        return false;
    }
    
    m_audioSource->start(m_audioIODevice);
    m_isCapturing = true;
    emit captureStatusChanged(true);
    
    qDebug() << "音频捕获已启动";
    return true;
}

void AudioCapture::stopCapture()
{
    if (!m_isCapturing) {
        return;
    }
    
    if (m_audioSource) {
        m_audioSource->stop();
    }
    
    m_isCapturing = false;
    emit captureStatusChanged(false);
    
    qDebug() << "音频捕获已停止";
}

bool AudioCapture::isCapturing() const
{
    return m_isCapturing;
}

void AudioCapture::setTransmissionEnabled(bool enabled)
{
    m_transmissionEnabled = enabled;
}

void AudioCapture::setTransmissionHost(const QString &host)
{
    m_transmissionHost = host;
}

void AudioCapture::setTransmissionPort(quint16 port)
{
    m_transmissionPort = port;
}

bool AudioCapture::startTransmission()
{
    if (!m_transmissionEnabled) {
        return false;
    }
    
    m_transmissionTimer->start(33); // 约30fps
    emit transmissionStatusChanged(true);
    
    qDebug() << "音频传输已启动";
    return true;
}

void AudioCapture::stopTransmission()
{
    m_transmissionTimer->stop();
    emit transmissionStatusChanged(false);
    
    qDebug() << "音频传输已停止";
}

bool AudioCapture::isTransmitting() const
{
    return m_transmissionEnabled && m_transmissionTimer->isActive();
}

void AudioCapture::setupAudioFormat()
{
    m_audioFormat.setSampleRate(SAMPLE_RATE);
    m_audioFormat.setChannelCount(CHANNEL_COUNT);
    m_audioFormat.setSampleFormat(QAudioFormat::Int16);
}

bool AudioCapture::initializeAudioCapture()
{
    // 获取默认音频输入设备
    QList<QAudioDevice> devices = QMediaDevices::audioInputs();
    if (devices.isEmpty()) {
        qCritical() << "没有可用的音频输入设备";
        return false;
    }
    
    m_audioDevice = devices.first();
    qDebug() << "使用音频设备:" << m_audioDevice.description();
    
    // 创建音频源
    m_audioSource = new QAudioSource(m_audioDevice, m_audioFormat, this);
    if (!m_audioSource) {
        qCritical() << "无法创建音频源";
        return false;
    }
    
    // 设置缓冲区大小
    m_audioSource->setBufferSize(BUFFER_SIZE);
    
    // 创建IO设备
    m_audioIODevice = m_audioSource->start();
    if (!m_audioIODevice) {
        qCritical() << "无法启动音频IO设备";
        return false;
    }
    
    // 连接信号
    connect(m_audioSource, &QAudioSource::stateChanged, this, &AudioCapture::onAudioSourceStateChanged);
    connect(m_audioIODevice, &QIODevice::readyRead, this, &AudioCapture::onAudioDataReady);
    
    return true;
}

void AudioCapture::onAudioDataReady()
{
    if (!m_audioIODevice) {
        return;
    }
    
    QByteArray data = m_audioIODevice->readAll();
    if (!data.isEmpty()) {
        processAudioData(data);
    }
}

void AudioCapture::onAudioSourceStateChanged(QAudio::State state)
{
    switch (state) {
    case QAudio::ActiveState:
        qDebug() << "音频源处于活动状态";
        break;
    case QAudio::SuspendedState:
        qDebug() << "音频源被暂停";
        break;
    case QAudio::StoppedState:
        qDebug() << "音频源已停止";
        break;
    case QAudio::IdleState:
        qDebug() << "音频源处于空闲状态";
        break;
    }
}

void AudioCapture::onTransmissionTimer()
{
    if (!m_transmissionEnabled) {
        return;
    }
    
    // 处理队列中的音频数据
    QMutexLocker locker(&m_audioQueueMutex);
    while (!m_audioQueue.isEmpty()) {
        QByteArray data = m_audioQueue.dequeue();
        locker.unlock();
        
        sendAudioData(data);
        
        locker.relock();
    }
}

void AudioCapture::processAudioData(const QByteArray &data)
{
    if (m_processingThread) {
        m_processingThread->addAudioData(data);
    }
    
    // 如果启用了传输，将数据添加到队列
    if (m_transmissionEnabled) {
        QMutexLocker locker(&m_audioQueueMutex);
        m_audioQueue.enqueue(data);
        
        // 限制队列大小
        while (m_audioQueue.size() > 10) {
            m_audioQueue.dequeue();
        }
    }
}

void AudioCapture::sendAudioData(const QByteArray &data)
{
    // 这里可以实现音频数据的网络传输
    // 例如通过TCP socket发送到WebSocket服务器
    emit audioDataReady(data);
}

// AudioProcessingThread 实现
AudioCapture::AudioProcessingThread::AudioProcessingThread(AudioCapture *parent)
    : QThread(parent)
    , m_parent(parent)
    , m_running(true)
{
}

void AudioCapture::AudioProcessingThread::addAudioData(const QByteArray &data)
{
    QMutexLocker locker(&m_queueMutex);
    m_dataQueue.enqueue(data);
    m_queueCondition.wakeOne();
}

void AudioCapture::AudioProcessingThread::stopProcessing()
{
    m_running = false;
    m_queueCondition.wakeAll();
}

void AudioCapture::AudioProcessingThread::run()
{
    while (m_running) {
        QMutexLocker locker(&m_queueMutex);
        
        while (m_dataQueue.isEmpty() && m_running) {
            m_queueCondition.wait(&m_queueMutex, 100); // 100ms超时
        }
        
        if (!m_running) {
            break;
        }
        
        if (!m_dataQueue.isEmpty()) {
            QByteArray data = m_dataQueue.dequeue();
            locker.unlock();
            
            // 处理音频数据
            // 这里可以添加音频处理逻辑，如降噪、压缩等
            
            emit audioDataProcessed(data);
        }
    }
}
